import React, { useEffect, useState, useMemo, useRef } from 'react';
import { Link, useLocation, withRouter } from 'react-router-dom';
import { Layout, Menu } from 'antd';
import styles from './style.less'
import logo from '@assets/logo.png'
import ResizeObserver from 'resize-observer-polyfill';
import * as Icon from '@ant-design/icons';
// import { IconFont } from '@utils/request.js';



const renderMenuItem = (routers = []) => {
    /**
    * 先筛选出path和name同时存在的路由，然后进行遍历出左侧菜单
    * 当前路由存在子路由且子路由也存在path和name，则渲染出SubMenu标签，内部再递归子路由
    * 否则渲染出Item标签
    * @author swh 
    */
    return routers
        .filter(item => item.path && item.name && item.icon)
        .map(subMenu => {
            if (subMenu.children && !!subMenu.children.find(child => child.path && child.name)) {
                return (
                    <Menu.SubMenu
                        key={subMenu.path}
                        icon={
                            React.createElement(
                                Icon[subMenu.icon], {
                                // style: { fontSize: '16px', color: '#08c' }
                            }
                            )
                            // <IconFont type={`${subMenu.icon}`} />
                        }
                        title={subMenu.name}
                    >
                        {renderMenuItem(subMenu.children)}
                    </Menu.SubMenu>
                )
            }
            return (
                <Menu.Item key={subMenu.path}
                    icon={
                        React.createElement(
                            Icon[subMenu.icon]
                        )
                        // <IconFont type={`${subMenu.icon}`} />
                    }
                    onClick={() => { localStorage.setItem('tabsKey', subMenu.path); localStorage.setItem('tabsTitle', subMenu.name) }}>
                    <Link to={subMenu.path} >
                        {subMenu.name}
                    </Link>
                </Menu.Item>
            )
        })
}


/**
 * pathname获取当前页面的路由，将pathname拆分成数组赋值给左侧菜单的key，当输入路由跳转后会自动展开左侧路由定位
 * useEffect监听pathname的变化后赋值给openKeys
 * useRef获取菜单的dom节点，ResizeObserver方法监听菜单的收缩变化
 * @author swh
 */

const SiderMenu = ({ routes, collapsed, onCollapsedChange, history, themeColor }) => {

    const { pathname } = useLocation();

    const [openKeys, setOpenKeys] = useState([]);


    /**
     * 该生命周期只监听pathname的变化，当路由改变时会自动调用获取路由的接口, 当没有子路由时弹回到登录页
     * useMemo避免多余的渲染，做部分优化
     */
    useEffect(() => {
        const list = pathname.split('/').splice(1);
        setOpenKeys(list.map((item, index) => `/${list.slice(0, index + 1).join('/')}`));
    }, [pathname])

    const getSelectedKeys = useMemo(() => {
        const list = pathname.split('/').splice(1);
        return list.map((item, index) => `/${list.slice(0, index + 1).join('/')}`);
    }, [pathname]);


    const onOpenChange = keys => {
        setOpenKeys(keys);
    };

    useEffect(() => {
        // if (routes.length === 0 && Array.isArray(routes)) {
        //     history.push('/login')
        // }
    }, [routes])

    /**
     * 使用ref获取左侧菜单div的dom节点
     * 在useEffect生命周期里在第一次渲染阶段先判断宽度，然后决定图标logo的位置
     * 用ResizeObserver监听菜单div的宽度变化
     * 最后卸载监听ResizeObserver的事件
     */

    const widthRef = useRef();

    useEffect(() => {

        if (widthRef.current.clientWidth > 48) {
            widthRef.current.style.textAlign = 'left'
        } else {
            widthRef.current.style.textAlign = 'center'
        }

        const observer = new ResizeObserver(function (mutations) {
            mutations.forEach(function (mutation) {
                if (mutation.contentRect.width > 48) {
                    widthRef.current.style.textAlign = 'left'
                } else {
                    widthRef.current.style.textAlign = 'center'
                }
            })
        })

        observer.observe(widthRef.current)

        return () => {
            observer.disconnect()
        }
    }, [])



    return (
        <Layout.Sider
            // style={{
            //     overflow: 'auto',
            //     height: '100vh',
            // }}
            trigger={null}
            theme={themeColor}
            // className={styles.selectFalse}
            collapsible collapsed={collapsed} onCollapse={(bool) => onCollapsedChange(bool)}
        >
            <Link to="/">
                <div className={styles.logo} ref={widthRef}>
                    <img src={logo} alt='logo' width='32px' height='32px' />
                    <span style={{ marginLeft: 10, color: "#1890ff" }}>
                        react admin
                    </span>
                </div>
            </Link>
            <Menu
                mode="inline"
                theme={themeColor}
                style={{ paddingLeft: 0, marginBottom: 0 }}
                openKeys={openKeys}
                onOpenChange={onOpenChange}
                selectedKeys={getSelectedKeys}
            >
                {renderMenuItem(routes)}
            </Menu>
        </Layout.Sider>
    )
}

export default withRouter(SiderMenu);